package top.datacluster.basic.algorithm.leetcode;

public class RotateLinkLeetcode61 {

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null){
            return head;
        }
        if (k == 0){
            return head;
        }

        ListNode index = head;
        ListNode end = head;
        int i = k;

        while (i > 0){
            if (end.next != null){
                end = end.next;
            }else{
                end = head;
            }
            i--;
        }

        while (end.next != null){
            index = index.next;
            end = end.next;
        }
        if (index.next == null){
            return head;
        }
        ListNode newHeader = index.next;
        index.next = null;
        end.next = head;
        return newHeader;

    }


    public static class ListNode{
        int val;

        ListNode next;

        ListNode(int x) { val = x; }
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(2);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
//        node2.next = node3;
//        node3.next = node4;
//        node4.next = node5;
        ListNode result = new RotateLinkLeetcode61().rotateRight(node1, 2);
        while (result != null){
            System.out.println(result.val);
            result = result.next;
        }

    }
}
